package server.net.handler;

import game.GameInstance;
import java.nio.ByteBuffer;
import java.util.HashMap;
import server.net.Client;
import server.net.ClientConnection;
import shared.net.protocol.PacketCreator;
import shared.util.Pair;

/**
 * Handles requests for a full game listing.
 *
 * Conditions: The client must be logged in.
 * 
 * @author Vincent Tsuei
 * @author Andrew Gratta
 * @author Nathan Poslusny
 * @version 2012-11-28
 */
public class GameListRequestHandler implements ServerPacketHandler {

    @Override
    public int processPacket(Client client, ByteBuffer packet) {
        if (client == null || packet == null)
        {
            return -1;
        }
        ClientConnection connection = client.getConnection();
        if (!client.isLoggedIn()) {
            connection.queuePacketSend(PacketCreator.LOBBY
                    .getGameListFailureResponse("Error: You must be logged in to view games"));
            return -1;
        }
        
        GameInstance[] games = client.getGameServer().getServerRegistry().getAllGames();
        HashMap<Long, Pair<String, String>> gamePlayerPairs = new HashMap<Long,Pair<String, String>>();
        for (int i = 0; i < games.length; i++)
        {
            Pair<String,String> gamePairs = new Pair(games[i].getFirstPlayer().getName(), 
                                           games[i].getSecondPlayer().getName());
            gamePlayerPairs.put(games[i].getGameID(), gamePairs);
        }
        connection.queuePacketSend(PacketCreator.LOBBY.getGameListResponse(gamePlayerPairs));    
        return 0;
        
    }
    
}
